package com.pachong.utils;

import com.pachong.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlPraseUtils {
    //测试用
    public static void main(String[] args) throws Exception {
        new HtmlPraseUtils().parseJD("java").forEach(System.out::println);
    }

    public List<Content> parseJD(String keywords) throws Exception {
        //获取请求，需联网
        String url = "https://search.jd.com/Search?keyword="+keywords;
        //解析网页 返回JS document页面
        Document document = Jsoup.parse(new URL(url), 30000);
        //JS里面使用的所有方法这里都能使用
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //获取元素中的内容，el是每一个li标签
        System.out.println("++++++++++++++++++++++++++++");
        System.out.println(element.html());
        //会将需要的网页数据保存到数组中
        ArrayList<Content> goodsList = new ArrayList<>();


        for (Element el : elements) {
            //图片多的网站，图片会有延迟加载
            //source-data-lazy-img
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
//            String commit = el.getElementsByClass("p-commit").eq(0).text();

            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
//            content.setCommit(commit);

            goodsList.add(content);

        }
        return goodsList;
    }

}
